package redis

import (
	"context"
	"fmt"
	"strconv"
	"user/user"
)

func CartAdd(GoodsId, UserId, Num, Stock int64, Title, CartCover string) error {

	sprintf := fmt.Sprintf("cart:%d", UserId)
	return Client.HMSet(context.Background(), sprintf, map[string]interface{}{
		"GoodsId":   GoodsId,
		"UserId":    UserId,
		"Num":       Num,
		"Stock":     Stock,
		"Title":     Title,
		"CartCover": CartCover,
	}).Err()
}

func CartList(UserId int64) (cartlist []*user.CartListStrcut) {

	sprintf := fmt.Sprintf("cart:%d", UserId)
	keys := Client.Keys(context.Background(), sprintf).Val()

	for _, v := range keys {

		HGetAll := Client.HGetAll(context.Background(), v).Val()
		GoodsId, _ := strconv.Atoi(HGetAll["GoodsId"])
		UserId, _ := strconv.Atoi(HGetAll["UserId"])
		Num, _ := strconv.Atoi(HGetAll["Num"])
		Stock, _ := strconv.Atoi(HGetAll["Stock"])
		Title, _ := HGetAll["Title"]
		CartCover, _ := HGetAll["CartCover"]

		cartlist = append(cartlist, &user.CartListStrcut{
			GoodsId:   int64(GoodsId),
			UserId:    int64(UserId),
			Num:       int64(Num),
			Stock:     int64(Stock),
			Title:     Title,
			CartCover: CartCover,
		})
	}
	return
}
